<template>
  <div class="login-page">
    <!-- <Test ref="test" />
    <button @click="fn">点击一下</button> -->
    <el-card>
      <template #header>黑马面经运营后台</template>
      <!--  el-form的使用
        1. 在el-form上绑定了model属性
        2. 在input上v-model双向绑定了数据
        3. 校验数据 => 通过 rules属性  在el-form-item上绑定prop属性
       -->
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="输入用户名" v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="输入用户密码"  v-model="form.password"></el-input>
        </el-form-item>

        <el-form-item class="tc">
          <el-button type="primary" @click="login">登 录</el-button>
          <el-button @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// import Test from '@/components/test.vue'
import { login } from '@/api/user'
export default {
  name: 'login-page',
  components: {
    // Test
  },
  data () {
    return {
      form: {
        username: 'admin5',
        password: 'admin'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 5, max: 11, message: '长度在5-11个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { pattern: /^\w{5,11}$/, message: '请输入5-11位的密码', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    // fn () {
    //   console.log(this.$refs)
    //   this.$refs.test.sayHi()
    // },
    async login () {
      // 登录的账号密码  admin(1-9)  admin
      // this.$refs.form.validate().then().catch()
      try {
        // validate 校验整个表单的方法(el-form组件提供的) 返回promise 改写成了async await
        const valid = await this.$refs.form.validate()
        console.log(valid)
        if (valid) {
          const res = await login(this.form)
          console.log('res', res)
          this.$store.commit('user/setUserToken', res.data.token)
          this.$router.push('/')
        }
      } catch (error) {
        console.log('error', error)
      }
    },
    reset () {
      // resetFields 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果(el-form组件提供的)
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header{
      height: 80px;
      background: rgba(114,124,245,1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
